package com.zq.springadmin.logs;

import com.zq.springadmin.dao.entity.SysOperLog;
import com.zq.springadmin.service.ISysOperLogService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * @Author 张乔
 * @Date 2024/5/29 13:44
 */
@Aspect
@Component
@Slf4j
public class AspectLogs {

    @Resource
    private ISysOperLogService saveSysOperLog;

    @Around(value = "@annotation(sysLogs)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint , sysLogs sysLogs) {
        // 构建前置参数
        SysOperLog sysOperLog = new SysOperLog() ;

        LogUtil.beforeHandleLog(sysLogs , joinPoint , sysOperLog) ;

        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
            // 执行业务方法
            LogUtil.afterHandlLog(sysLogs , proceed , sysOperLog , 0 , null) ;
            // 构建响应结果参数
        } catch (Throwable e) {                                 // 代码执行进入到catch中，
            // 业务方法执行产生异常
            e.printStackTrace();                                // 打印异常信息
            LogUtil.afterHandlLog(sysLogs , proceed , sysOperLog , 1 , e.getMessage()) ;
//        抛出异常，让全局异常处理
            throw new RuntimeException();
        }

        // 保存日志数据
        saveSysOperLog.save(sysOperLog);
//        asyncOperLogService.saveSysOperLog(sysOperLog);
//LogService.send(sysOperLog);

        // 返回执行结果
        return proceed ;// 返回执行结果
    }

}
